﻿using Microsoft.AspNetCore.Mvc;
using NSwag.Annotations;
using ProxyServer.EntityFrameworkCore;
using ProxyServer.Quartz.Jobs;
using Quartz;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http.HttpResults;
using ProxyServer.Quartz;

namespace ProxyServer.Endpoints
{
    public static class EventEndpoints
    {
        [OpenApiOperation(nameof(CheckAccount), "", "")]
        public static async Task CheckAccount([FromServices] ISchedulerFactory schedulerFactory, CancellationToken cancellationToken)
        {
            var schd = await schedulerFactory.GetScheduler(cancellationToken);
            await schd.TriggerJob(CheckAccountJob.Key, cancellationToken);
        }

        [OpenApiOperation(nameof(CheckService), "", "")]
        public static async Task<Results<Ok, NotFound>> CheckService([FromServices] ISchedulerFactory schedulerFactory, [FromRoute] Guid id, [FromServices] AppDbContext db, [FromQuery] bool reCreate, CancellationToken cancellationToken)
        {
            var schd = await schedulerFactory.GetScheduler(cancellationToken);

            var exists = await db.Services.AnyAsync(x => x.Id == id, cancellationToken);
            if (exists == false)
            {
                return TypedResults.NotFound();
            }

            // var jobKey = CheckServiceCertificateJob.BuildServiceJobKey(id);

            // var trigger = TriggerBuilder.Create()
            //     .WithIdentity("once")
            //     .ForJob(jobKey)
            //     .WithSimpleSchedule(opt =>
            //     {
            //         opt.WithRepeatCount(0);
            //         opt.WithInterval(TimeSpan.FromSeconds(10));
            //     })
            //     .UsingJobData(new JobDataMap { [CheckServiceCertificateJob.ReCreateOrder] = reCreate })
            //     .Build();


            // await schd.ScheduleJob(trigger, cancellationToken);

            await QuartzHelpers.StartCheckSerivceCertificateOnce(schd, id, cancellationToken);

            return TypedResults.Ok();
        }
    }
}
